package com.centaline.androidsalesblog.base;

import android.content.Intent;
import android.os.Bundle;

import com.android.volley.VolleyError;
import com.centaline.androidsalesblog.api.SinaUserInfoApi;
import com.centaline.androidsalesblog.api.WxAuthApi;
import com.centaline.androidsalesblog.api.WxUserInfoApi;
import com.centaline.androidsalesblog.api.usercenter.LoginApi;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.model.businissobject.QqUserInfoBo;
import com.centaline.androidsalesblog.model.businissobject.SinaUserInfoBo;
import com.centaline.androidsalesblog.model.businissobject.WxAuthBo;
import com.centaline.androidsalesblog.model.businissobject.WxUserInfoBo;
import com.centaline.androidsalesblog.model.databaseobject.QqAuthDo;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.UserRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.interfaces.IResponseListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.orhanobut.logger.Logger;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.trello.rxlifecycle.ActivityEvent;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 登录基类,需要使用第三方登录的页面使用
 * Created by guilin on 16/4/8.
 */
public abstract class BaseLoginActivity extends BaseActivity {

    protected final Gson gson = new Gson();
    protected boolean loginWx;

    /*微信*/
    private IWXAPI iwxapi;

    /*QQ*/
    protected Tencent tencent;
    private IUiListener iUiListener = new IUiListener() {
        @Override
        public void onComplete(Object o) {
            Logger.d("onComplete : %s", o.toString());
            try {
                QqAuthDo qqAuthDo = gson.fromJson(o.toString(), QqAuthDo.class);
                tencent.setOpenId(qqAuthDo.getOpenid());
                tencent.setAccessToken(qqAuthDo.getAccess_token(), String.valueOf(qqAuthDo.getExpires_in()));
                requestQqUserInfo();
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
                authError();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Logger.d("uiError : %s", uiError.errorDetail);
            errorMessage(uiError.errorMessage);
        }

        @Override
        public void onCancel() {
            userCancel();
        }
    };

    /*新浪*/
    protected AuthInfo authInfo;
    protected SsoHandler ssoHandler;
    protected WeiboAuthListener weiboAuthListener = new WeiboAuthListener() {
        @Override
        public void onComplete(Bundle bundle) {
            Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(bundle);
            if (accessToken.isSessionValid()) {
                requestSinaUserInfo(accessToken);
            } else {
                authError();
            }
        }

        @Override
        public void onWeiboException(WeiboException e) {
            errorMessage(e.getMessage());
        }

        @Override
        public void onCancel() {
            userCancel();
        }
    };

    /**
     * 显示错误信息
     */
    private void errorMessage(String message) {
        cancelLoadingDialog();
        snack(message);
    }

    /**
     * 授权出错
     */
    private void authError() {
        cancelLoadingDialog();
        snack("授权出错");
    }

    /**
     * 用户取消
     */
    protected void userCancel() {
        cancelLoadingDialog();
        snack("用户取消");
    }

    /**
     * 微信登录
     */
    protected void wXLogin() {
        if (iwxapi == null) {
            iwxapi = WXAPIFactory.createWXAPI(this, CommonConstant.APP_ID_WX);
        }
        if (!iwxapi.isWXAppInstalled()) {
            toast("微信未安装");
        }
        iwxapi.registerApp(CommonConstant.APP_ID_WX);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "zyzf_wx_login";
        iwxapi.sendReq(req);
    }

    /**
     * 微信授权获取accessToken
     */
    protected void requestWxAuth(String code) {
        WxAuthApi wxAuthApi = new WxAuthApi(getClass(), WxAuthBo.class, new IResponseListener<WxAuthBo>() {
            @Override
            public void onResponse(WxAuthBo wxAuthBo) {
                if (wxAuthBo != null) {
                    requestWxUserInfo(wxAuthBo.getAccess_token(), wxAuthBo.getOpenid());
                } else {
                    authError();
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        wxAuthApi.setCode(code);
        wxAuthApi.startRequest();
    }

    /**
     * 微信用户信息获取
     */
    private void requestWxUserInfo(String accessToken, String openId) {
        WxUserInfoApi wxUserInfoApi = new WxUserInfoApi(getClass(), WxUserInfoBo.class,
                new IResponseListener<WxUserInfoBo>() {
                    @Override
                    public void onResponse(WxUserInfoBo wxUserInfoBo) {
                        if (wxUserInfoBo != null) {
                            login(0, wxUserInfoBo.getOpenid(), wxUserInfoBo.getNickname(), wxUserInfoBo.getHeadimgurl());
                        } else {
                            authError();
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        netWorkUnable();
                    }
                });
        wxUserInfoApi.setAccessToken(accessToken);
        wxUserInfoApi.setOpenId(openId);
        wxUserInfoApi.startRequest();
    }

    /**
     * qq登录
     */
    protected void qqLogin() {
        showLoadingDialog();
        if (tencent == null) {
            tencent = Tencent.createInstance(CommonConstant.APP_ID_QQ, this);
        }
        qqAuth();
    }

    /**
     * qq授权
     */
    private void qqAuth() {
        tencent.login(this, "all", iUiListener);
    }

    /**
     * 请求qq用户信息
     */
    private void requestQqUserInfo() {
        UserInfo userInfo = new UserInfo(this, tencent.getQQToken());
        userInfo.getUserInfo(new IUiListener() {
            @Override
            public void onComplete(Object o) {
                try {
                    QqUserInfoBo qqUserInfoBo = gson.fromJson(o.toString(), QqUserInfoBo.class);
                    login(1, tencent.getOpenId(), qqUserInfoBo.getNickname(), qqUserInfoBo.getFigureurlQq2());
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                    authError();
                }
            }

            @Override
            public void onError(UiError uiError) {
                errorMessage(uiError.errorMessage);
            }

            @Override
            public void onCancel() {
                userCancel();
            }
        });
    }

    /**
     * sina登录
     */
    protected void sinaLogin() {
        showLoadingDialog();
        if (authInfo == null) {
            authInfo = new AuthInfo(this, CommonConstant.APP_KEY_SINA,
                    CommonConstant.REDIRECT_URL,
                    CommonConstant.SCOPE_SIAN);

        }
        if (ssoHandler == null) {
            ssoHandler = new SsoHandler(this, authInfo);
        }
        ssoHandler.authorize(weiboAuthListener);
    }

    /**
     * 新浪用户信息请求
     */
    private void requestSinaUserInfo(Oauth2AccessToken accessToken) {
        SinaUserInfoApi sinaUserInfoApi = new SinaUserInfoApi(getClass(),
                accessToken,
                SinaUserInfoBo.class,
                new IResponseListener<SinaUserInfoBo>() {
                    @Override
                    public void onResponse(SinaUserInfoBo sinaUserInfoBo) {
                        if (sinaUserInfoBo != null) {
                            login(2,
                                    sinaUserInfoBo.getIdstr(),
                                    sinaUserInfoBo.getScreen_name(),
                                    sinaUserInfoBo.getProfile_image_url());
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        cancelLoadingDialog();
                        netWorkUnable();
                    }
                });
        sinaUserInfoApi.setUid(accessToken.getUid());
        sinaUserInfoApi.startRequest();
    }

    /**
     * 中原登录api
     *
     * @param loginType  第三方登录类型 0:微信;1:QQ;2:新浪
     * @param account    帐户id
     * @param nickName   昵称
     * @param profileUrl 头像地址
     */
    private void login(int loginType, String account, String nickName, String profileUrl) {
        LoginApi loginApi = new LoginApi(getClass(), UserRo.class, new IResponseListener<UserRo>() {
            @Override
            public void onResponse(UserRo userRo) {
                UserDo userDo = userRo.getUserDo();
                if (userRo.getResultNo() != 0 ||
                        userDo == null) {
                    cancelLoadingDialog();
                    snack(userRo.getMessage());
                } else {
                    AppConstant.setUserLogin(BaseLoginActivity.this, userDo);
                    userSave(userDo);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        switch (loginType) {
            case 0:
                loginApi.setWeiXinAccount(account);
                break;
            case 1:
                loginApi.setQqAccount(account);
                break;
            case 2:
                loginApi.setSinaAccount(account);
                break;
            default:
                break;
        }
        loginApi.setNickName(nickName);
        loginApi.setThirdLoginPicUrl(profileUrl);
        loginApi.startRequest();
    }

    /**
     * 第三方登录成功
     */
    protected void otherLoginSuccess() {
        cancelLoadingDialog();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case Constants.REQUEST_LOGIN://qq登录
                    Tencent.onActivityResultData(requestCode, resultCode, data, iUiListener);
                    break;
                case Constants.REQUEST_API:
                    //qq
                case 32973:
                    if (ssoHandler != null) {
                        ssoHandler.authorizeCallBack(requestCode, resultCode, data);
                    }
                    break;
                default:
                    break;
            }
        } else {
            cancelLoadingDialog();
        }
    }

    /**
     * 保存用户信息
     */
    private void userSave(UserDo userDo) {
        AppConstant.setUserLogin(this, userDo);
        RxDataBase.saveUser(userDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        otherLoginSuccess();
                    }
                });
    }
}
